package com.chiffoyqc.utils;

import com.chiffoyqc.config.BaseConfig;
import org.apache.log4j.helpers.DateTimeDateFormat;
import org.springframework.util.Base64Utils;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

/**
 * Created by Administrator on 2017/6/19.
 */
public class HttpHelper {

    public static final String AUTHORIZATION = "Authorization";

    /**
     * @Description:使用HttpURLConnection发送get请求
     * @author:liuyc
     * @time:2016年5月17日 下午3:27:29
     */
    public static String sendGet(String urlParam, String charset) {
        StringBuffer resultBuffer = null;
        // 构建请求参数
//        StringBuffer sbParams = new StringBuffer();
        HttpURLConnection con = null;
        BufferedReader br = null;
        try {
            URL url = new URL(urlParam);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.connect();
            resultBuffer = new StringBuffer();
            br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
            String temp;
            while ((temp = br.readLine()) != null) {
                resultBuffer.append(temp);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            CloseSource.closeCloseableSource(br);
            if (con != null) {
                con.disconnect();
                con = null;
            }
        }
        return resultBuffer.toString();
    }

    public static String sendPostForNormal(String urlParam, String params, String charset) {
        StringBuffer resultBuffer = null;
        // 构建请求参数
//        StringBuffer sbParams = new StringBuffer();

        HttpURLConnection con = null;
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        // 发送请求
        try {
            URL url = new URL(urlParam);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            osw = new OutputStreamWriter(con.getOutputStream(), charset);
            osw.write(params);
            osw.flush();
            // 读取返回内容
            resultBuffer = new StringBuffer();
            int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
            if (contentLength > 0) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
                String temp;
                while ((temp = br.readLine()) != null) {
                    resultBuffer.append(temp);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            CloseSource.closeCloseableSource(osw, br);
            if (con != null) {
                con.disconnect();
                con = null;
            }
        }

        return resultBuffer.toString();
    }

    /**
     * @Description:使用HttpURLConnection发送post请求
     * @author:liuyc
     * @time:2016年5月17日 下午3:26:07
     */
    public static String sendPostForRMIS(String urlParam, String params, String charset) {
        StringBuffer resultBuffer = null;
        // 构建请求参数
        StringBuffer sbParams = new StringBuffer();

        HttpURLConnection con = null;
        OutputStreamWriter osw = null;
        BufferedReader br = null;
        // 发送请求
        try {
            URL url = new URL(urlParam);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Accept", "application/json");
            con.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateStr = simpleDateFormat.format(date);

            /**生成AccessToken*/
            //appId + appSecret + 时间戳
            sbParams.setLength(0);
            sbParams.append(BaseConfig.APPID).append(BaseConfig.APPSECRET).append(dateStr);

            //使用 MD5 加密
            String accessToken = MD5Utils.md5Password(sbParams.toString());
            con.setRequestProperty("AccessToken", accessToken);

            /**生成Authorization*/
            //（appId + 冒号(英文) + 时间戳）
            sbParams.setLength(0);
            sbParams.append(BaseConfig.APPID).append(":").append(dateStr);

            //使用 Base64 编码
            String authorization = Base64Util.encode(sbParams.toString());
            con.setRequestProperty(AUTHORIZATION, authorization);

            /**发送信息*/
            osw = new OutputStreamWriter(con.getOutputStream(), charset);
            osw.write(params);
            osw.flush();

            /**接收返回信息*/
            resultBuffer = new StringBuffer();
            int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
            if (contentLength > 0) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
                String temp;
                while ((temp = br.readLine()) != null) {
                    resultBuffer.append(temp);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            CloseSource.closeCloseableSource(osw, br);
            if (con != null) {
                con.disconnect();
                con = null;
            }
        }

        return resultBuffer.toString();
    }

    /**
     * 回复request请求所得数据
     * */
    public static void responseData(HttpServletResponse response ,String data) {
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(data.getBytes("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            CloseSource.closeCloseableSource(outputStream);
        }

    }

    public static void responseDataForRMIS(HttpServletResponse response ,Object data) {
//        ServletOutputStream outputStream = null;
        PrintWriter writer = null;
        try {
            response.setHeader("content-type", "application/json;charset=UTF-8");

            writer = response.getWriter();
            writer.print(data);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
//            CloseSource.closeCloseableSource(writer);
            writer.close();
        }

    }

    /**
     * 获取当前网络真实ip
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 获取post数据
     * */
    public static String getPostData(ServletRequest request){
        StringBuffer stringBuffer = null;
        try {
            ServletInputStream inputStream = request.getInputStream();
//                BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            stringBuffer = new StringBuffer();
            char[] chars = new char[1024];
            int len;
            while ((len = bufferedReader.read(chars)) != -1){
                stringBuffer.append(chars,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(stringBuffer != null && stringBuffer.length() != 0){
            return stringBuffer.toString();
        }
        return null;
    }

}
